﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

using XCode;
using BingZi.HY.Core;
using XCode.Common;
using System.Web.UI.WebControls;
using BingZi.WebControls;
using System.Data;
 
 




namespace BingZi.HY.Core
{
    /// <summary>分类信息</summary>
    [ModelCheckMode(ModelCheckModes.CheckTableWhenFirstUse)]
    public class app_Category : app_Category<app_Category>, IDropDownTree { }

    /// <summary>分类信息</summary>
    public partial class app_Category<TEntity> : Entity<TEntity> where TEntity : app_Category<TEntity>, IDropDownTree, new()
    {
        #region 扩展属性﻿
        #endregion

        #region 扩展查询﻿
        /// <summary>
        /// 根据主键查询一个分类信息实体对象用于表单编辑
        /// </summary>
        /// <param name="categoryid">分类ID号</param>
        /// <returns></returns>
        [DataObjectMethod(DataObjectMethodType.Select, false)]
        public static TEntity FindByKeyForEdit(Int32 categoryid)
        {
            TEntity entity = Find(new String[] { _.CategoryID }, new Object[] { categoryid });
            if (entity == null)
            {
                entity = new TEntity();
            }
            return entity;
        }


        /// <summary>
        /// 根据分类ID号查找
        /// </summary>
        /// <param name="categoryid">分类ID号</param>
        /// <returns></returns>
        [DataObjectMethod(DataObjectMethodType.Select, false)]
        public static TEntity FindByCategoryID(Int32 categoryid)
        {
            if (Meta.Count >= 1000)
                return Find(new String[] { _.CategoryID }, new Object[] { categoryid });
            else // 实体缓存
                return Meta.Cache.Entities.Find(_.CategoryID, categoryid);
            // 单对象缓存
            //return Meta.SingleCache[categoryid];
        }
        #endregion

        #region 对象操作﻿
        ///// <summary>
        ///// 已重载。基类先调用Valid(true)验证数据，然后在事务保护内调用OnInsert
        ///// </summary>
        ///// <returns></returns>
        //public override Int32 Insert()
        //{
        //    return base.Insert();
        //}

        ///// <summary>
        ///// 已重载。在事务保护范围内处理业务，位于Valid之后
        ///// </summary>
        ///// <returns></returns>
        //protected override Int32 OnInsert()
        //{
        //    return base.OnInsert();
        //}

        ///// <summary>
        ///// 验证数据，通过抛出异常的方式提示验证失败。
        ///// </summary>
        ///// <param name="isNew"></param>
        //public override void Valid(Boolean isNew)
        //{
        //    // 建议先调用基类方法，基类方法会对唯一索引的数据进行验证
        //    base.Valid(isNew);

        //    // 这里验证参数范围，建议抛出参数异常，指定参数名，前端用户界面可以捕获参数异常并聚焦到对应的参数输入框
        //    if (String.IsNullOrEmpty(_.Name)) throw new ArgumentNullException(_.Name, _.Name.Description + "无效！");
        //    if (!isNew && ID < 1) throw new ArgumentOutOfRangeException(_.ID, _.ID.Description + "必须大于0！");

        //    // 在新插入数据或者修改了指定字段时进行唯一性验证，CheckExist内部抛出参数异常
        //    if (isNew || Dirtys[_.Name]) CheckExist(_.Name);
        //    if (isNew || Dirtys[_.Name] || Dirtys[_.DbType]) CheckExist(_.Name, _.DbType);
        //    if ((isNew || Dirtys[_.Name]) && Exist(_.Name)) throw new ArgumentException(_.Name, "值为" + Name + "的" + _.Name.Description + "已存在！");
        //}


        ///// <summary>
        ///// 首次连接数据库时初始化数据，仅用于实体类重载，用户不应该调用该方法
        ///// </summary>
        //[EditorBrowsable(EditorBrowsableState.Never)]
        //protected override void InitData()
        //{
        //    base.InitData();

        //    // InitData一般用于当数据表没有数据时添加一些默认数据，该实体类的任何第一次数据库操作都会触发该方法，默认异步调用
        //    // Meta.Count是快速取得表记录数
        //    if (Meta.Count > 0) return;

        //    // 需要注意的是，如果该方法调用了其它实体类的首次数据库操作，目标实体类的数据初始化将会在同一个线程完成
        //    if (XTrace.Debug) XTrace.WriteLine("开始初始化{0}管理员数据……", typeof(TEntity).Name);

        //    TEntity user = new TEntity();
        //    user.Name = "admin";
        //    user.Password = DataHelper.Hash("admin");
        //    user.DisplayName = "管理员";
        //    user.RoleID = 1;
        //    user.IsEnable = true;
        //    user.Insert();

        //    if (XTrace.Debug) XTrace.WriteLine("完成初始化{0}管理员数据！", typeof(TEntity).Name);
        //}
        #endregion

        #region 高级查询

        /// <summary>
        /// 显示所有子级级菜单
        /// </summary>
        /// <returns></returns>
        public static EntityList<TEntity> ViewFindChild(Object ParentID)
        {
            NewLife.QueryParam qp = new NewLife.QueryParam();
            qp.Orderfld = _.C_ShowOrder;
            qp.OrderType = 0;
            qp.Where.Add(new NewLife.SearchParam(_.C_ParentID, ParentID, NewLife.SearchType.Equal));
            int RecordCount = 0;
            return FindAll(qp, out RecordCount);
        }


        /// <summary>
        /// 按编号查询子集
        /// </summary>
        /// <param name="id">分类编号</param>
        /// <returns></returns>
        public static String FindIDs(Int32 id)
        {
            XCode.DataAccessLayer.DAL dal = XCode.DataAccessLayer.DAL.Create(Meta.ConnName);
            System.Text.StringBuilder sb = new StringBuilder();
            sb.AppendFormat("with Category as(select *,0 as rank from {0} where CategoryID = {1} union all select h.*,h1.rank+1 from {0} h join Category h1 on h.C_ParentID=h1.CategoryID)", Meta.TableName, id).AppendLine();
            sb.AppendFormat("select * from Category", Meta.TableName);
            DataSet ds = dal.Select(sb.ToString(), new String[] { "Category" });
            
            System.Text.StringBuilder IDs = new StringBuilder();
            EntityList<TEntity> List = LoadData(ds);
            if (List != null && List.Count > 0)
            {
                foreach (TEntity li in List)
                {
                    IDs.AppendFormat("{0}{1}", IDs.Length == 0 ? "" : ",", li.CategoryID);
                }
            }
            return IDs.ToString();
        }


        // 以下为自定义高级查询的例子

        ///// <summary>
        ///// 查询满足条件的记录集，分页、排序
        ///// </summary>
        ///// <param name="key">关键字</param>
        ///// <param name="orderClause">排序，不带Order By</param>
        ///// <param name="startRowIndex">开始行，0表示第一行</param>
        ///// <param name="maximumRows">最大返回行数，0表示所有行</param>
        ///// <returns>实体集</returns>
        //[DataObjectMethod(DataObjectMethodType.Select, true)]
        //public static EntityList<TEntity> Search(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
        //{
        //    return FindAll(SearchWhere(key), orderClause, null, startRowIndex, maximumRows);
        //}

        ///// <summary>
        ///// 查询满足条件的记录总数，分页和排序无效，带参数是因为ObjectDataSource要求它跟Search统一
        ///// </summary>
        ///// <param name="key">关键字</param>
        ///// <param name="orderClause">排序，不带Order By</param>
        ///// <param name="startRowIndex">开始行，0表示第一行</param>
        ///// <param name="maximumRows">最大返回行数，0表示所有行</param>
        ///// <returns>记录数</returns>
        //public static Int32 SearchCount(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
        //{
        //    return FindCount(SearchWhere(key), null, null, 0, 0);
        //}

        /// <summary>
        /// 构造搜索条件
        /// </summary>
        /// <param name="key">关键字</param>
        /// <returns></returns>
        private static String SearchWhere(String key)
        {
            // WhereExpression重载&和|运算符，作为And和Or的替代
            WhereExpression exp = new WhereExpression();

            // SearchWhereByKeys系列方法用于构建针对字符串字段的模糊搜索
            if (!String.IsNullOrEmpty(key)) SearchWhereByKeys(exp.Builder, key);

            // 以下仅为演示，2、3行是同一个意思的不同写法，FieldItem重载了等于以外的运算符（第4行）
            //exp &= _.Name.Equal("testName")
            //    & !String.IsNullOrEmpty(key) & _.Name.Equal(key)
            //    .AndIf(!String.IsNullOrEmpty(key), _.Name.Equal(key))
            //    | _.ID > 0;

            return exp;
        }


        /// <summary>
        /// 显示所有菜的那
        /// </summary>
        /// <returns></returns>
        public static EntityList<TEntity> ViewFindAll()
        {
            NewLife.QueryParam qp = new NewLife.QueryParam();
            qp.Where.Add(new NewLife.SearchParam(_.C_State,1, NewLife.SearchType.Equal));

            int RecordCount = 0;
            return FindAll(qp,out RecordCount);
        }



        #endregion

        #region 扩展操作
        #endregion

        #region 业务


        /// <summary>
        /// 获取部门标题路径
        /// </summary>
        /// <param name="CategoryID">部门ID</param>
        /// <returns></returns>
        public static string GetCategoryTitle(int CategoryID)
        {
            int TotalRecord = 0;
            NewLife.QueryParam qp = new NewLife.QueryParam();
            List<NewLife.SearchParam> sps = new List<NewLife.SearchParam>();
            sps.Add(new NewLife.SearchParam(_.CategoryID, CategoryID, NewLife.SearchType.Equal));
            qp.Where = sps;
            qp.PageIndex = 1;
            qp.PageSize = 1;
            EntityList<TEntity> lst = FindAll(qp, out TotalRecord);
            if (TotalRecord == 1)
            {

                foreach (TEntity x in lst)
                {
                    return GetCategoryTitle(x.C_ParentID) + ">" + string.Format("<a href='CategoryList.aspx?CategoryID={0}'>{1}</a>", x.CategoryID, x.C_Name);
                }
            }
            return "";
        }
        /// <summary>
        /// 排序分类ID子分类
        /// </summary>
        /// <param name="CategoryID">分类ID</param>
        public static void app_Category_By(int CategoryID)
        {
            int RecordCount = 0;
            NewLife.QueryParam qp = new NewLife.QueryParam();
            qp.Orderfld = "C_Level,C_ShowOrder";
            qp.OrderType = 0;
            List<NewLife.SearchParam> sps = new List<NewLife.SearchParam>();
            sps.Add(new NewLife.SearchParam(app_Category._.C_State, (int)EnumState.Normal,NewLife.SearchType.Equal));
            sps.Add(new NewLife.SearchParam(app_Category._.C_ParentID, CategoryID, NewLife.SearchType.Equal));
            qp.Where = sps;
            EntityList<TEntity> lst = FindAll(qp, out RecordCount);
            RecordCount = 1;
            foreach (TEntity var in lst)
            {
                var.C_ShowOrder = RecordCount;
                var.Update();
                RecordCount++;
            }
        }

        /// <summary>
        /// 获取当前分类及子分类列表以,号分开
        /// </summary>
        /// <param name="CategoryID">部门ID</param>
        /// <returns></returns>
        public static string GetCategoryCatID(int CategoryID)
        {
            string All_ID = CategoryID.ToString();
            EntityList<TEntity> lst = FindAll(_.C_ParentID, CategoryID);
            if (lst.Count > 0)
            {
                foreach (TEntity x in lst)
                {
                    All_ID = string.Format("{0},{1}", All_ID, GetCategoryCatID(x.CategoryID));
                }
            }
            return All_ID;
        }



        /// <summary>
        /// 生成刷新菜单列表js
        /// </summary>
        public static string BuildJs
        {
            get
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<script language=javascript>");
                sb.Append("window.parent.leftbody.location.reload();");
                sb.Append("</script>");

                return sb.ToString();
            }
        }
        /// <summary>
        /// 生成分类JS脚本
        /// </summary>
        /// <returns></returns>
        public static string app_CategoryBindJs()
        {
            //存储JS的字符串
            string s = string.Empty;
            int RecordCount = 0;

            NewLife.QueryParam qp = new NewLife.QueryParam();
            qp.Orderfld = "C_Level,C_ShowOrder";
            qp.OrderType = 0;
            //读取第一个节点的分类
            List<NewLife.SearchParam> sps = new List<NewLife.SearchParam>();
            sps.Add(new NewLife.SearchParam(app_Category._.C_State, (int)EnumState.Normal, NewLife.SearchType.Equal));
            sps.Add(new NewLife.SearchParam(app_Category._.C_ParentID, 0, NewLife.SearchType.Equal));
            qp.Where = sps;

            EntityList<TEntity> lst = FindAll(qp, out RecordCount);

            for (int i = 0; i < lst.Count; i++)
            {
                TEntity app = lst[i];

                s = string.Format("{0}\nT = new TopCategory('{1}','{2}') \n topCatArr = topCatArr.concat(T)", s, app.CategoryID, app.C_Name);

                app_CategoryBindJsSecond(ref s, app.CategoryID);
            }

            return s;
        }
        public static void app_CategoryBindJsSecond(ref string var, int ParentID)
        {
            int RecordCount = 0;
            NewLife.QueryParam qp = new NewLife.QueryParam();
            qp.Orderfld = "C_Level,C_ShowOrder";
            qp.OrderType = 0;
            //读取第二个节点的分类
            List<NewLife.SearchParam> sps = new List<NewLife.SearchParam>();
            sps.Add(new NewLife.SearchParam(app_Category._.C_State, (int)EnumState.Normal, NewLife.SearchType.Equal));
            sps.Add(new NewLife.SearchParam(app_Category._.C_ParentID, ParentID, NewLife.SearchType.Equal));
            qp.Where = sps;

            EntityList<TEntity> lst = FindAll(qp, out RecordCount);
            for (int i = 0; i < lst.Count; i++)
            {
                TEntity app = lst[i];
                var = string.Format("{0}\n S = new CA(T,'{1}','{2}')", var, app.CategoryID, app.C_Name);

                app_CategoryBindJsLeaf(ref var, app.CategoryID);
            }
        }

        public static void app_CategoryBindJsLeaf(ref string var, int ParentID)
        {
            int RecordCount = 0;
            NewLife.QueryParam qp = new NewLife.QueryParam();
            qp.Orderfld = "C_Level,C_ShowOrder";
            qp.OrderType = 0;
            //读取第三个节点的分类
            List<NewLife.SearchParam> sps = new List<NewLife.SearchParam>();
            sps.Add(new NewLife.SearchParam(app_Category._.C_State, (int)EnumState.Normal, NewLife.SearchType.Equal));
            sps.Add(new NewLife.SearchParam(app_Category._.C_ParentID, ParentID, NewLife.SearchType.Equal));
            qp.Where = sps;

            EntityList<TEntity> lst = FindAll(qp, out RecordCount);
            for (int i = 0; i < lst.Count; i++)
            {
                TEntity app = lst[i];

                var = string.Format("{0}\n new L(S,'{1}','{2}')", var, app.CategoryID, app.C_Name);
            }
        }

		#endregion


        #region 继承实现下拉树菜单

        /// <summary>
        /// 根据当前用户取出列表
        /// </summary>
        /// <returns>分类列表</returns>
        public static List<object> GetListTree()
        {
            List<TEntity> lst = FindAll();
            List<object> olst = new List<object>();

            //增加一个默认的
            TEntity app = new TEntity();
            app.CategoryID = 0;
            app.C_ParentID = -1;

            if (lst.Count > 0)
                app.C_Name = "暂不分类";
            else
                app.C_Name = "未增加分类";

            olst.Add(app);


            foreach (TEntity li in lst)
                olst.Add(li);

            return olst;
        }


        /// <summary>
        /// 获取下级分类信息
        /// </summary>
        /// <param name="parentID"></param>
        /// <param name="lst"></param>
        /// <returns></returns>
        public Dictionary<string, string> GetChildCategory(string parentID, List<Object> lst)
        {
            Dictionary<string, string> categoryList = new Dictionary<string, string>();
            for (int i = 0; i < lst.Count; i++)
            {
                app_Category app = (app_Category)lst[i];
                if (app._C_ParentID.ToString() == parentID)
                {
                    categoryList.Add(Convert.ToString(app.CategoryID), Convert.ToString(app.C_Name));
                }
            }
            return categoryList;
        }

        /// <summary>
        /// 下拉树对象
        /// </summary>
        public DropDownTree DropDownTree
        {
            get { return new DropDownTree(this); }
        }

        /// <summary>
        /// 绑定下拉列表
        /// </summary>
        /// <param name="ddl"></param>
        /// <param name="lst"></param>
        public static void BindDropDownTree(DropDownList ddl, List<object> lst)
        {
            new app_Category().DropDownTree.BindToDropDownList(ddl, string.Empty, "-1", lst);
        }


        #region IDisposable 成员
        /// <summary>
        /// IDisposable 成员
        /// </summary>
        public void Dispose()
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        #endregion

        #endregion
	}
}